package com.cershy.chatroomserver.service;

import cn.hutool.json.JSONObject;
import com.cershy.chatroomserver.entity.User;
import com.cershy.chatroomserver.exception.ChatException;
import com.cershy.chatroomserver.utils.CacheUtil;
import com.cershy.chatroomserver.utils.JwtUtil;
import com.cershy.chatroomserver.vo.login.LoginVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class LoginService {


    @Resource
    UserService userService;

    @Resource
    CacheUtil cacheUtil;




    public JSONObject login(LoginVo loginVo) {
        User user = userService.getUserByName(loginVo.getName());

        if (user == null) {
            throw new ChatException("用户名不存在，请先注册");
        }

        if (loginVo.getName().equals(user.getName()) &&
                !loginVo.getPassword().equals(user.getPassword())) {
            throw new ChatException("密码错误~");
        }

        user.setLoginTime(new Date());
        userService.updateById(user);

        JSONObject userinfo = new JSONObject();
        userinfo.put("type", "user");
        userinfo.put("userId", user.getId());
        userinfo.put("userName", user.getName());
        userinfo.put("email", user.getEmail());
        userinfo.put("avatar", user.getAvatar());
        String token = JwtUtil.createToken(userinfo);
        userinfo.put("token", token);
        cacheUtil.putUserSessionCache(user.getId(), token);


        return userinfo;
    }


}
